<script setup lang="ts">
import { ref, onMounted } from "vue"
import { del } from "@/utils/request"
import { ElMessage, ElMessageBox } from "element-plus"
import { emptyPet, listPets, type PetBreed, petTypeList, type Pet, type PetType, petBreedList, addPet, delPet, searchPetNameToServer } from "@/api/pets"
import { getUser } from "@/utils/auth"
import { Plus } from '@element-plus/icons-vue'
import PetDetail from "./PetDetail.vue"


/* =========================
   新增：列表/详情切换
   ========================= */
const viewMode = ref<"list" | "detail">("list")
const currentPet = ref<Pet | null>(null)

const uploadUrl = import.meta.env.MODE === 'development' ? "/api/api/upload/pet/avatar" : "/api/upload/pet/avatar"
const uploadHeaders = {
    Authorization: "Bearer " + (getUser()?.token ?? '')
}

const openDetail = (pet: Pet) => {
    currentPet.value = pet
    viewMode.value = "detail"
}

const backToList = () => {
    viewMode.value = "list"
}

/* ========== 数据 ========== */
const pets = ref<Pet[]>([])
const loading = ref(false)
// 宠物类型数组
const typeList = ref<PetType[]>([]);
// 宠物品种数组
const breedList = ref<PetBreed[]>([]);
const searchName = ref("")
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const addDialog = ref(false)

const form = ref<Pet>(emptyPet())

/* ========== 表单规则（重点） ========== */
const rules = {
    name: [
        { required: true, message: "请输入宠物名字", trigger: "blur" },
        { min: 1, max: 20, message: "名字长度 1-20 字", trigger: "blur" }
    ],
    type: [
        { required: true, message: "请选择宠物类型", trigger: "change" }
    ],
    breed: [
        { required: true, message: "请选择品种", trigger: "change" }
    ],
    gender: [
        { required: true, message: "请选择性别", trigger: "change" }
    ],
    remark: [
        { required: false, message: "请填写描述", trigger: "blur" }
    ],
}

/* ========== 获取宠物列表 ========== */
const loadPets = async () => {
    loading.value = true

    const res = await listPets({ pageNum: pageNum.value, pageSize: pageSize.value })
    const page = res.data

    pets.value = page.list || []
    total.value = page.total || 0

    loading.value = false
}

const searchPetName = async () => {
    if (searchName.value === '') {
        ElMessage.error("请输入需要查询的宠物名称!!!")
        return
    }

    loading.value = true
    const res = await searchPetNameToServer({ pageNum: pageNum.value, pageSize: pageSize.value, name: searchName.value })
    const page = res.data

    pets.value = page.list || []
    total.value = page.total || 0
    loading.value = false
}

/* 获取宠物类型 */
const loadTypes = async () => {
    const res = await petTypeList();
    typeList.value = res.data;
};

/* 获取宠物品种 */
const loadBreed = async (petTypeId: number) => {
    const res = await petBreedList({ petTypeId })
    breedList.value = res.data
}

/** 处理获取宠物品种 */
const handleChangePetTypeToBreed = async (petTypeId: number) => {
    breedList.value = [];
    await loadBreed(petTypeId);
    console.log("breed list: {}", breedList)
    form.value.breed = breedList.value[0]?.id ?? 0;
}

/* ========== 分页事件处理 ========== */

const handleSizeChange = (size: number) => {
    pageSize.value = size
    loadPets()
}

const handlePageChange = (num: number) => {
    pageNum.value = num
    loadPets()
}


/* ========== 添加宠物 ========== */

const savePet = async () => {
    // console.log("form: {}", form.value);

    const res = await addPet(form.value);

    if (res.code == 200) {
        ElMessage.success(res.msg)
    }
    else {
        ElMessage.error(res.msg);
    }

    addDialog.value = false

    form.value = emptyPet();

    loadPets()
}

/* 点击添加宠物按钮 */
const clickedAddPet = async () => {
    form.value = emptyPet();
    addDialog.value = true
    await loadTypes();
    form.value.type = typeList.value[0]?.id ?? 0
    await handleChangePetTypeToBreed(form.value.type)
}

/* 限制头像 */
const beforeAvatarUpload = (file: File) => {
    const isJpgPng = file.type === "image/jpeg" || file.type === "image/png"
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJpgPng) {
        ElMessage.error("头像必须是 JPG/PNG 格式!")
        return false;
    }
    if (!isLt2M) {
        ElMessage.error("头像大小不能超过 2MB!")
        return false;
    }

    return isJpgPng && isLt2M
}

/* 上传头像结果 */
const handleAvatarSuccess = (res: any) => {
    console.log("res: {}", res);

    form.value.avatar = res.data.url;
    ElMessage.success("上传成功");
}

/* ========== 删除宠物 ========== */
const removePet = async (id: number) => {
    ElMessageBox.confirm("确定要删除这只宠物吗？", "提示", { type: "warning" })
        .then(async () => {
            // await del(`/api/pet/delete/${id}`)
            const res = await delPet(id);
            if (res.code == 200) {
                ElMessage.success(res.msg);
            }
            else {
                ElMessage.error(res.msg);
            }
            loadPets()
        })
}

/* ========== 初始化 ========== */
onMounted(loadPets)
</script>

<!-- ======================================
       模板开始：新增（详情 + 列表切换）
     ====================================== -->
<template>

    <!-- ================== 详情界面 ================== -->
    <div v-if="viewMode === 'detail'" class="detail-page">
        <PetDetail :pet-id="currentPet!.id" :onBack="backToList" />
    </div>

    <!-- ================== 列表界面 ================== -->
    <div v-else class="page">
        <!-- 顶部栏 -->
        <div class="header">
            <h2>我的宠物</h2>
            <div class="actions">
                <el-input v-model="searchName" placeholder="请输入宠物名称" clearable @clear="loadPets" @keyup.enter="loadPets"
                    style="width: 220px" />

                <el-button type="primary" @click="searchPetName">查询</el-button>
                <el-button type="success" @click="clickedAddPet">添加宠物</el-button>
            </div>
        </div>

        <!-- 宠物卡片列表 -->
        <div class="pet-list" v-loading="loading">
            <el-empty v-if="pets.length === 0" description="暂无宠物" />

            <el-card v-for="p in pets" :key="p.id" :body-style="{ padding: '0px' }" class="pet-card" shadow="hover">
                <div style="display: flex; flex-direction: column;  padding: 10px; height: auto; width: 100%;">
                    <div class="pet-card-body">
                        <img :src="p.avatar" class="avatar" />
                        <div class="card-pet-info">
                            <div>
                                <el-tag round class="tag-name">姓名：{{ p!.name }}</el-tag>
                            </div>

                            <div class="detail-tags">
                                <el-tag round type="info">性别：{{ p!.gender === 1 ? "公" : "母" }}</el-tag>
                            </div>

                            <!-- 新增：生日标签 -->
                            <div class="detail-tags">
                                <el-tag round type="warning">
                                    生日：{{ p!.birthday?.slice(0, 10) }}
                                </el-tag>
                            </div>

                            <!-- 新增：品种标签 -->
                            <div class="detail-tags">
                                <el-tag round type="primary">{{ p!.breedString || "未填写" }}</el-tag>
                                <el-tag round type="success">{{ p!.typeString || "未填写" }}</el-tag>
                            </div>
                        </div>
                        <div class="card-option">
                            <div>
                                <el-button link type="primary" @click.stop="openDetail(p)">详情</el-button>
                            </div>
                            <div>
                                <el-button link type="danger" @click.stop="removePet(p.id)">删除</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
            <el-pagination background layout="prev, pager, next, sizes, total" :current-page="pageNum"
                :page-size="pageSize" :total="total" @size-change="handleSizeChange"
                @current-change="handlePageChange" />
        </div>

        <!-- 添加宠物弹窗 -->
        <el-dialog v-model="addDialog" title="添加宠物" width="480px" class="add-dialog">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" class="pet-form">
                <!-- 名字 -->
                <el-form-item label="名字" prop="name">
                    <el-input v-model="form.name" placeholder="请输入宠物名字" clearable />
                </el-form-item>
                <!-- 类型 -->
                <el-form-item label="类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择宠物类型" clearable @change="handleChangePetTypeToBreed">
                        <el-option v-for="t in typeList" :key="t.id" :label="t.name" :value="t.id" />
                    </el-select>
                </el-form-item>
                <!-- 品种 -->
                <el-form-item label="品种" prop="breed">
                    <el-select v-model="form.breed" placeholder="请选择品种" clearable>
                        <el-option v-for="t in breedList" :key="t.id" :label="t.name" :value="t.id" />
                    </el-select>
                </el-form-item>
                <!-- 性别 -->
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="form.gender" placeholder="请选择性别">
                        <el-option label="公" :value="1" />
                        <el-option label="母" :value="2" />
                    </el-select>
                </el-form-item>
                <!-- 生日 -->
                <el-form-item label="生日" prop="birthday">
                    <el-date-picker v-model="form.birthday" type="date" placeholder="请选择生日和时间"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <!-- 头像上传 -->
                <el-form-item label="头像">
                    <el-upload class="avatar-uploader" :headers="uploadHeaders" :action="uploadUrl"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <!-- 宠物描述 -->
                <el-form-item label="描述" prop="remark">
                    <el-input type="textarea" v-model="form.remark" placeholder="请输入宠物的性格 / 特点 / 备注信息" :rows="3"
                        resize="none" maxlength="200" show-word-limit />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addDialog = false">取消</el-button>
                    <el-button type="primary" @click="savePet">保存</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<style scoped>
/********************* 列表样式 *********************/
.page {
    padding: 10px 15px;
    display: flex;
    flex-direction: column;
    min-height: calc(100vh - 60px);
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    flex-shrink: 0;
    height: auto;
}

.actions {
    display: flex;
    gap: 10px;
}

.pet-list {
    display: flex;
    flex-wrap: wrap;
    gap: 22px;
}

.pet-card {
    width: 320px;
    display: flex;
    flex-direction: column;
    padding: 5px;
    border-radius: 16px;
    background-color: aliceblue;
    /* background-color: #409eff; */
}

.pet-card-body {
    display: flex;
    flex-direction: row;
    width: 100%;
    gap: 5px;
}

.card-pet-info {
    display: flex;
    height: auto;
    width: auto;
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
    /* background-color:aqua; */
}

.avatar {
    width: 120px;
    height: 120px;
    border-radius: 10px;
    margin-right: 12px;
    align-self: center;
}

.pagination {
    margin-top: auto;
    text-align: center;
}


/********************* 详情样式 *********************/
.detail-page {
    padding: 10px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.detail-card {
    max-width: 600px;
    margin: 20px auto;
    padding: 25px;
    border-radius: 18px;
}

.detail-avatar {
    width: 180px;
    height: 180px;
    border-radius: 14px;
    object-fit: cover;
    box-shadow: 0 4px 15px rgba(0, 0, 0, .1);
}

.detail-name {
    text-align: center;
    font-size: 28px;
    margin: 10px 0;
}

.detail-tags {
    display: flex;
    justify-content: center;
    gap: 10px;
}

.detail-info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    row-gap: 15px;
    margin-top: 10px;
}

.detail-info-grid label {
    font-size: 13px;
    color: #888;
}

.detail-remark {
    margin-top: 15px;
}

.detail-remark p {
    background: #fafafa;
    border-radius: 10px;
    padding: 15px;
    line-height: 1.6;
}

.add-dialog ::v-deep(.el-dialog) {
    border-radius: 12px;
}

.pet-form .el-form-item {
    margin-bottom: 18px;
}

.dialog-footer {
    text-align: right;
    padding: 10px 0;
}

.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 10px;
    object-fit: cover;
}

.avatar-uploader .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 10px;
}

.avatar-uploader .avatar-uploader-icon:hover {
    border-color: #409eff;
}

/* 标签 */
.tags {
    display: flex;
    justify-content: center;
    gap: 10px;
}

.tag {
    padding: 5px 12px;
    font-size: 14px;
}

.tag-name {
    background-color: #f3e8ff;
    /* 淡紫 */
    color: #7b3fe4;
    /* 高级紫 */
    border-color: #e0c8ff;
}

.card-option {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    /* 垂直居中 */
    align-items: flex-start;
    /* ⭐ 靠右 */
    gap: 5px;
    /* background-color: #7b3fe4; */
    /* flex-shrink: 0; */
    width: auto;
}
</style>
